package com.vertx.config;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.ext.consul.ConsulClient;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;


public class KeyStoreVerticle extends AbstractVerticle {


	public static void main(String[] args) {
		Runner.runExample(KeyStoreVerticle.class);
	}


	@Override
	public void start(Promise<Void> startPromise) throws Exception {


		Router router = Router.router(vertx);
		router.route().handler(BodyHandler.create());

		router.post("/key/:key").handler(this::saveKeyAndValue);
		router.get("/key/:key").handler(this::getKey);

		vertx.createHttpServer().requestHandler(router).listen(8080);

	}

	private void saveKeyAndValue(RoutingContext context) {
		String key = context.request().getParam("key");
		String value = context.getBodyAsString();

		ConsulClient client = ConsulClient.create(vertx);

		client.putValue(key, value, res -> {
			if (res.succeeded()) {
				String opResult = res.result() ? "success" : "fail";
				System.out.println("result of the operation: " + opResult);
			} else {
				res.cause().printStackTrace();
			}
		});
	}


	private void getKey(RoutingContext context) {
		String key = context.request().getParam("key");

		ConsulClient client = ConsulClient.create(vertx);

		client.getValue(key, res -> {
			if (res.succeeded()) {
				System.out.println("retrieved value: " + res.result().getValue());
			} else {
				res.cause().printStackTrace();
			}
		});
	}
}